// controllers/categoryController.js
const db = require('../config/db');

const categoryController = {
  // 获取店铺的菜品分类
  getCategoriesByShop: async (req, res) => {
    try {
      const { shopId } = req.params;
      console.log('获取菜品分类，店铺ID:', shopId);

      // 直接查询该店铺的分类
      const query = `
        SELECT * 
        FROM categories 
        WHERE shop_id = ? AND is_active = TRUE
        ORDER BY sort_order, name
      `;
      
      const [categories] = await db.execute(query, [shopId]);

      console.log(`店铺 ${shopId} 的菜品分类数量:`, categories.length);

      res.json({
        success: true,
        message: '获取菜品分类成功',
        data: categories
      });

    } catch (error) {
      console.error('获取菜品分类失败:', error);
      res.status(500).json({
        success: false,
        message: '获取菜品分类失败',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  },

  // 获取分类下的菜品
  getDishesByCategory: async (req, res) => {
    try {
      const { shopId, categoryId } = req.params;
      console.log('获取菜品，店铺ID:', shopId, '分类ID:', categoryId);

      // 验证分类是否属于该店铺
      const categoryCheckQuery = 'SELECT id FROM categories WHERE id = ? AND shop_id = ?';
      const [categoryCheck] = await db.execute(categoryCheckQuery, [categoryId, shopId]);

      if (categoryCheck.length === 0) {
        return res.status(404).json({
          success: false,
          message: '分类不存在或不属于该店铺'
        });
      }

      const query = `
        SELECT d.*, c.name as category_name
        FROM dishes d 
        INNER JOIN categories c ON d.category_id = c.id 
        WHERE d.shop_id = ? AND d.category_id = ? AND d.status = 'active'
        ORDER BY d.sort_order, d.name
      `;
      
      const [dishes] = await db.execute(query, [shopId, categoryId]);

      console.log(`分类 ${categoryId} 的菜品数量:`, dishes.length);

      res.json({
        success: true,
        message: '获取菜品成功',
        data: dishes
      });

    } catch (error) {
      console.error('获取菜品失败:', error);
      res.status(500).json({
        success: false,
        message: '获取菜品失败',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  },

  // 获取店铺的所有菜品（按分类分组）
  getAllDishesByShop: async (req, res) => {
    try {
      const { shopId } = req.params;
      console.log('获取所有菜品，店铺ID:', shopId);

      // 先获取分类
      const categoriesQuery = `
        SELECT * 
        FROM categories 
        WHERE shop_id = ? AND is_active = TRUE
        ORDER BY sort_order, name
      `;
      
      const [categories] = await db.execute(categoriesQuery, [shopId]);

      // 为每个分类获取菜品
      const categoriesWithDishes = await Promise.all(
        categories.map(async (category) => {
          const dishesQuery = `
            SELECT * 
            FROM dishes 
            WHERE shop_id = ? AND category_id = ? AND status = 'active'
            ORDER BY sort_order, name
          `;
          
          const [dishes] = await db.execute(dishesQuery, [shopId, category.id]);
          
          return {
            ...category,
            dishes: dishes
          };
        })
      );

      console.log(`店铺 ${shopId} 的分类数量:`, categoriesWithDishes.length);

      res.json({
        success: true,
        message: '获取菜品数据成功',
        data: categoriesWithDishes
      });

    } catch (error) {
      console.error('获取所有菜品失败:', error);
      res.status(500).json({
        success: false,
        message: '获取菜品数据失败',
        error: process.env.NODE_ENV === 'development' ? error.message : undefined
      });
    }
  }
};

module.exports = categoryController;